//
//  MineMessageController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/9/30.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "MineMessageController.h"
#import "MineMessageSafeController.h"
#import "CorePhotoPickerVCManager.h"
#import "UIButton+WebCache.h"

@interface MineMessageController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,copy) UITableView *tableView;
@property (nonatomic,copy) NSArray *titleArr;
@property (nonatomic,copy) NSArray *contentArr;
@property (nonatomic,strong) UIButton *headBtn;
@property (nonatomic,assign) float heightOfFirstCell;
@property (nonatomic,copy) UIImage *headerImg;
@end

@implementation MineMessageController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBack];
    [self createSubViews];
}

#pragma mark ==========创建视图==========
- (void)createSubViews{
    self.view.backgroundColor = [UIColor whiteColor];
    self.heightOfFirstCell = 195*SCALEUNIT;
    self.title = @"我的信息";
    self.titleArr = @[@"头像",@"真实姓名",@"我的驾校",@"执教科目",@"执教车型",@"账号安全"];
    self.contentArr = @[[UserMessage sharedInstance].model.name==nil?@"":[UserMessage sharedInstance].model.name,[UserMessage sharedInstance].model.schoolName==nil?@"":[UserMessage sharedInstance].model.schoolName,[UserMessage sharedInstance].model.zjkm==nil?@"":[self returnCarType:[UserMessage sharedInstance].model.zjkm],[UserMessage sharedInstance].model.teachCarType==nil?@"":[UserMessage sharedInstance].model.teachCarType];
    [self.view addSubview:self.tableView];
}

- (UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SYSTEM_TOP, SCREEN_WIDTH, SCREEN_HEIGHT - SYSTEM_TOP) style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 30*SCALEUNIT, 0, 30*SCALEUNIT)];
        [_tableView setSeparatorColor:RGBA(230, 230, 230, 1)];
    }
    return _tableView;
}

- (UIButton *)headBtn{
    if (!_headBtn) {
        _headBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _headBtn.frame = CGRectMake(0, 0, 150*SCALEUNIT, 150*SCALEUNIT);
        _headBtn.center = CGPointMake(SCREEN_WIDTH-105*SCALEUNIT, self.heightOfFirstCell*0.5);
        _headBtn.layer.masksToBounds = YES;
        _headBtn.layer.cornerRadius = 150*SCALEUNIT*0.5;
        if ([[UserMessage sharedInstance].model.imgPath isEqualToString:@""]) {
            [_headBtn setImage:[UIImage imageNamed:[UserMessage sharedInstance].model.gender==0?@"MineGirlImage":@"MineBoyImage"] forState:UIControlStateNormal];
        } else {
            [_headBtn sd_setImageWithURL:[NSURL URLWithString:[UserMessage sharedInstance].model.imgPath] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:[UserMessage sharedInstance].model.gender==0?@"MineGirlImage":@"MineBoyImage"]];
        }
        [_headBtn addTarget:self action:@selector(headerChange:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headBtn;
}


#pragma mark ==========UITableView代理方法==========
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return self.heightOfFirstCell;
    }
    return 95*SCALEUNIT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineMessageController"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"MineMessageController"];
        cell.textLabel.textColor = RGBA(70, 70, 70, 1);
        cell.textLabel.font = [UIFont systemFontOfSize:LoginFont-2];
    }
    cell.textLabel.text = self.titleArr[indexPath.row];
    if (indexPath.row == 5){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            if (![cell.subviews containsObject:self.headBtn]) {
                [cell addSubview:self.headBtn];
            }
        }else {
            cell.detailTextLabel.textColor = RGBA(70, 70, 70, 1);
            cell.detailTextLabel.font = [UIFont systemFontOfSize:LoginFont-2];
            cell.detailTextLabel.text = self.contentArr[indexPath.row-1];
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==5) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self.navigationController pushViewController:[[MineMessageSafeController alloc] init] animated:YES];
    }else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

#pragma mark ==========更换头像==========
- (void)headerChange:(UIButton *)btn{
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:nil
                                                                            message:nil
                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alerController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 处理点击拍照
        [self alertActionWithIndex:0];
    }]];
    [alerController addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 处理相册
        [self alertActionWithIndex:1];
        
    }]];
    [alerController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alerController animated:YES completion:nil];
}

#pragma mark ==========相册回调==========
- (void)alertActionWithIndex:(NSInteger)buttonIndex {
    CorePhotoPickerVCMangerType type = 0;
    if (buttonIndex == 0) type = CorePhotoPickerVCMangerTypeCamera;
    if (buttonIndex == 1) type = CorePhotoPickerVCMangerTypeMultiPhoto;
    CorePhotoPickerVCManager *manger = [CorePhotoPickerVCManager sharedCorePhotoPickerVCManager];
    // 设置类型
    manger.pickerVCManagerType = type;
    // 最多可选择的张数
    manger.maxSelectedPhotoNumber = 1;
    
    if (manger.unavailableType != CorePhotoPickerUnavailableTypeNone) {
        [self showError:@"设备不可用"];
        return;
    }
    UIViewController *pickerVC = manger.imagePickerController;
    // 选取结束
    WS(ws);
    manger.finishPickingMedia = ^(NSArray *medias) {
        [medias enumerateObjectsUsingBlock:^(CorePhoto *photo, NSUInteger idx, BOOL * stop) {
            NSURL * refURL = photo.referenceURL;
            ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
            {
                ws.headerImg = photo.editedImage;
                [ws upPicDataMessage];
            };
            ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
            [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
        }];
    };
    [self presentViewController:pickerVC animated:YES completion:nil];
}

#pragma mark ==========上传头像==========
- (void)upPicDataMessage{
    [self userIcon:self.headerImg success:^(id responseObject) {
        [self showSuccess:[responseObject objectForKey:@"msg"]];
        if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
            self.block(self.headerImg);
            [UserMessage sharedInstance].model = [UserModel mj_objectWithKeyValues:[responseObject objectForKey:@"data"]];
            [[NSUserDefaults standardUserDefaults] setObject:[responseObject objectForKey:@"data"] forKey:@"userMessage"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self performSelector:@selector(headerChange) withObject:nil afterDelay:1.5f];
        }
    } failure:^(NSString *error) {
        [self showError:error];
    }];
}
- (void)headerChange{
    
    [self.headBtn setImage:self.headerImg forState:UIControlStateNormal];
}

#pragma mark 修改头像
- (void)userIcon:(UIImage *)imageIcon
         success:(void (^)(id responseObject))success
         failure:(void (^)(NSString  *error))failure
{
    NSString *postURL = [NSString stringWithFormat:@"%@%@", NETWORK_URL, @"authc/app/coach/coach/uploadImg"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.responseSerializer = response;
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer  setValue:[UserMessage sharedInstance].model.token forHTTPHeaderField:@"Authorization"];
    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    
    [manager POST:postURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        NSData *imageData =UIImageJPEGRepresentation(imageIcon, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObject) {
        NSDictionary *JSON = (NSDictionary *)responseObject;
        if ([JSON isKindOfClass:[NSDictionary class]]) {
            if ([[JSON allKeys] containsObject:@"code"]) {
                NSInteger status = [[JSON objectForKey:@"code"] integerValue];
                if (status == 1) {
                    if (success) success(JSON);
                }else if (status == 2) {
                    if (success) success(JSON);
                }else {
                    NSString *message = [JSON objectForKey:@"msg"];
                    if (![message isKindOfClass:[NSString class]]) message = @"";
                    if (failure) failure(message);
                }
            }else {
                if (success) success(JSON);
            }
        }
        else {
            if (failure) failure(@"返回数据错误，请联系开发");
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        NSString *message = [error localizedDescription];
        if (![message isKindOfClass:[NSString class]]) message = @"";
        if ([message length] <= 0) message = @"";
        if ([message isEqualToString:@"The Internet connection appears to be offline."]) message = @"网络连接有问题，请确认后重试";
        if (failure) failure(message);
    }];
}

#pragma mark ==========解析执教科目==========
- (NSString *)returnCarType:(NSString *)carTypeNum{
    NSString *carType;
    NSInteger car = [carTypeNum integerValue];
    if (carTypeNum>0) {
        if (carTypeNum.length==1) {
            carType = [self returnSolution:car%10];
        } else if (carTypeNum.length==2){
            carType = [NSString stringWithFormat:@"%@、%@",[self returnSolution:car/10],[self returnSolution:car%10]];
        } else if (carTypeNum.length==3){
            carType = [NSString stringWithFormat:@"%@、%@、%@",[self returnSolution:car/100],[self returnSolution:car/10%10],[self returnSolution:car%10]];
        } else if (carTypeNum.length==4){
            carType = [NSString stringWithFormat:@"%@、%@、%@、%@",[self returnSolution:car/1000],[self returnSolution:car/100%10],[self returnSolution:car/10%10],[self returnSolution:car%10]];
        }else{}
    }
    return carType;
}
- (NSString *)returnSolution:(NSInteger)num{
    NSArray *typeArr = @[@"科目一",@"科目二",@"科目三",@"科目四"];
    return [typeArr objectAtIndex:num-1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
